//
//  SRConnectVc.m
//  sr01sdkProject
//
//  Created by   on 2022/5/7.
//  about ble scan and connect

#import "CAConnectVc.h"
#import "CABLeService.h"
#import <Toast.h>
#import "CABLeService+Desc.h"
#import "LTPHud.h"
#import "ConfigModel.h"
/**
 * Connection + Authentication Process
 *  1 call [[LTSRingSDK instance] connectDevice:]
 *  2 caBleDeviceDidReadyForReadAndWrite call back,  call [[LTSRingSDK instance] functionGetDeviceInfo]
 *  3 caBleDeviceInfo: call back, call  [[LTSRingSDK instance] functionGetDeviceSN];
 *  4 "- (void)caBleOEMAuthResult:(BOOL)authSucceddful" callback and  authSucceddful == YES
 */

@interface CAConnectVc ()<UITableViewDelegate, UITableViewDataSource, CABleScanProtocal, CABleDataProtocal>

@property(strong, nonatomic)UITableView *tableView;
@property(strong, nonatomic)NSArray<CABLeService *>  *dataArray;

@end

@implementation CAConnectVc

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    WEAK_SELF
    [self customNavStyleNormal:@"Search Device" BackBlk:^{
        STRONG_SELF
        
        [strongSelf popVC];
    }];
    
    [self customNavRightBtn:@"refresh" BackBlk:^{
        STRONG_SELF
        strongSelf.dataArray = nil;
        [strongSelf.tableView reloadData];
        [[CARingSDK instance] stopBleScan];
        [CARingSDK.instance setCurrentPeripheralService:nil];// important

        [[CARingSDK instance] startBleScanWithOption:nil];
        
    }];
    [self initUI];
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [CARingSDK instance].blescanDelegate = self;  // scan delegate
    [CARingSDK instance].bleDataDelegate = self;
    [CARingSDK.instance setCurrentPeripheralService:nil];// important
    [[CARingSDK instance] startBleScanWithOption:nil]; // starting search ble device
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [[CARingSDK instance] stopBleScan]; // stop ble scan
}

-(void)initUI {
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.trailing.equalTo(self.view);
        make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
    }];
}

#pragma mark -tableveiw

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"connecttable"];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"connecttable"];
    }
    
    CABLeService *device = self.dataArray[indexPath.row];
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.text = device.boradCastInfomations;//device.advDataLocalName;
    cell.detailTextLabel.font = [UIFont systemFontOfSize:16];
    if (device.macAddress.length) {
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@:%@", _L2(L_TX_MAC_ADDR),device.macAddress];
        
    }

    
    return cell;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 160.f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [[CARingSDK instance] stopBleScan];
    
    [LTPHud.Instance showHudLasting:10];
    [[CARingSDK instance] connectDevice:self.dataArray[indexPath.row]];
    
}

-(void)popVC {
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark --SRBleDataProtocal


- (void)caBleDidConnectPeripheral:(nonnull CABLeService *)service {
    
    [LTPHud.Instance showText:@"Ring connect successfully"];
    
}

- (void)caBleDidDisconnectPeripheral:(nonnull CABLeService *)service {
    [LTPHud.Instance showText:@"Ring disconnected."];

}

- (void)caBleDeviceDidReadyForReadAndWrite:(nonnull CABLeService *)service {
    // get ring's infomation
    [[CARingSDK instance] functionGetDeviceInfo];
    
}

- (void)caBleDeviceInfo:(nonnull CADeviceInfo *)devInfo {
    
    [[CARingSDK instance] functionGetDeviceSN]; // for oem auth
    
}

- (void)caBleOEMAuthResult:(BOOL)authSucceddful
{
    if (authSucceddful) {
        [LTPHud.Instance showText:@"Ring OEM verification successful."];
        [self popVC];
    } else {
        [LTPHud.Instance showText:@"Ring OEM verification failed."];

    }

}





- (void)caBleIsBinded:(BOOL)isBinded
{
    
    DebugNSLog(@"%s isbind: %d", __FUNCTION__, isBinded);
}


#pragma mark --SRBleScanProtocal
/// scan device list fresh
/// @param perphelArray  scaned devices
-(void)caScanDeviceDidRefresh:(NSArray<CABLeService *> *)perphelArray
{
    // found devices
    self.dataArray = perphelArray;
    [self.tableView reloadData];
    
}


/// phone ble power state change
/// @param isOn  YES = powerOn NO = pwoerNO
- (void)caBlePowerStateChange:(CBManagerState)state {
    
}


-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        //        [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"connecttable"];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

@end
